<template>
  <div class="login-body">
    <div class="bg-item"></div>
    <div class="login-panel">
      <el-form
        class="login-form"
        :model="formData"
        :rules="rules"
        ref="formDataRef"
        @submit.prevent
      >
        <div class="login-title">LiteCloud</div>
        <!-- 邮箱 -->
        <el-form-item prop="email">
          <el-input
            type="email"
            size="large"
            clearable
            placeholder="请输入邮箱"
            v-model.trim="formData.email"
            maxlength="80"
          >
            <template #prefix>
              <span class="iconfont icon-account"></span>
            </template>
          </el-input>
        </el-form-item>
        <!-- 登录密码 -->
        <el-form-item
          prop="password"
          v-if="opType == 1"
        >
          <el-input
            type="password"
            size="large"
            placeholder="请输入密码"
            v-model.trim="formData.password"
            maxlength="80"
            show-password
          >
            <template #prefix>
              <span class="iconfont icon-password"></span>
            </template>
          </el-input>
        </el-form-item>
        <!-- 注册 -->
        <div v-if="opType == 0 || opType == 2">
          <el-form-item prop="emailCode">
            <div class="send-email-panel">
              <el-input
                placeholder="请输入邮箱验证码 "
                v-model.trim="formData.emailCode"
                size="large"
              >
                <template #prefix>
                  <span class="iconfont icon-checkcode"></span>
                </template>
              </el-input>
              <el-button
                class="send-email-btn"
                type="primary"
                @click="getEmailCode"
              >获取验证码</el-button>


            </div>
            <el-popover
              placement="left"
              :width="500"
              trigger="click"
            >
              <div>
                <p>请在邮箱的【垃圾箱】中查找邮箱验证码。</p>
                <p>在邮箱中通过以下路径设置白名单：头像 → 设置 → 反垃圾 → 白名单​​。</p>
                <p>将邮箱 2086155836@qq.com 添加到白名单</p>
              </div>
              <template #reference>
                <span class="a-link">未收到邮箱验证码？</span>
              </template>
            </el-popover>

          </el-form-item>
          <!-- 昵称 -->
          <el-form-item
            prop="nickName"
            v-if="opType == 0"
          >
            <el-input
              size="large"
              placeholder="请输入昵称"
              v-model.trim="formData.nickName"
              maxlength="20"
            >
              <template #prefix>
                <span class="iconfont icon-account"></span>
              </template>
            </el-input>
          </el-form-item>
          <!-- 找回密码 注册密码 -->
          <el-form-item prop="registerPassword">
            <el-input
              size="large"
              type="password"
              placeholder="请输入密码"
              v-model.trim="formData.registerPassword"
              show-passwords
            >
              <template #prefix>
                <span class="iconfont icon-password"></span>
              </template>
            </el-input>

          </el-form-item>
          <!-- 重复密码 -->
          <el-form-item prop="reRegisterPassword">
            <el-input
              size="large"
              type="password"
              placeholder="请再次输入密码"
              v-model.trim="formData.reRegisterPassword"
              show-password
            >
              <template #prefix>
                <span class="iconfont icon-password"></span>
              </template>
            </el-input>

          </el-form-item>
        </div>
        <!-- 验证码 -->
        <el-form-item prop="checkCode">
          <div class="checkCode-panel">
            <el-input
              size="large"
              placeholder="请输入验证码"
              v-model.trim="formData.checkCode"
              maxlength="80"
              @keyup.enter="doSubmit"
            >
              <template #prefix>
                <span class="iconfont icon-checkcode"></span>
              </template>
            </el-input>
            <img
              :src="checkCodeUrl"
              class="check-code"
              @click="changeCheckCode(0)"
            >
          </div>
        </el-form-item>
        <!-- 额外操作 -->
        <el-form-item>
          <div style="display: block; width: 100%;">
            <div class="remember-me">
              <el-checkbox v-model="formData.rememberMe">记住我</el-checkbox>
            </div>
            <div class="no-account">
              <a
                v-if="opType == 1"
                href="javascript:void(0)"
                class="a-link"
                @click="showPanel(0)"
              >注册</a>
              <a
                v-if="opType == 1"
                href="javascript:void(0)"
                class="a-link"
                @click="showPanel(2)"
              >忘记密码</a>
              <a
                v-if="opType == 0 || opType == 2"
                href="javascript:void(0)"
                class="a-link"
                @click="showPanel(1)"
              >去登录</a>
            </div>
          </div>

        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-btn"
            @click="doSubmit"
          >
            <span v-if="opType == 0">注册</span>
            <span v-if="opType == 1">登录</span>
            <span v-if="opType == 2">重置密码</span>

          </el-button>
        </el-form-item>
        <div
          class="login-btn-qq"
          v-if="opType == 1"
        >
          快捷登录<img
            src="../assets/qq.jpg"
            @click="qqLogin"
          >
        </div>

      </el-form>
    </div>
    <Dialog
      :show="dialogConfig.show"
      :title="dialogConfig.title"
      :buttons="dialogConfig.buttons"
      width="500px"
      :showCancel="false"
      @close="dialogConfig.show = false"
    >
      <el-form
        :model="formDataSendEmail"
        :rules="rules"
        ref="formDataSendEmailRef"
        label-width="80px"
        @submit.prevent
      >
        <!--input输入-->
        <el-form-item label="邮箱">
          {{ formData.email }}
        </el-form-item>
        <!--input输入-->
        <el-form-item
          label="验证码"
          prop="checkCode"
        >
          <div class="checkCode-panel">
            <el-input
              size="large"
              placeholder="请输入验证码"
              v-model.trim="formDataSendEmail.checkCode"
              maxlength="80"
            >
              <template #prefix>
                <span class="iconfont icon-checkcode"></span>
              </template>
            </el-input>
            <img
              :src="checkCodeUrlSendEmail"
              class="check-code"
              @click="changeCheckCode(1)"
            >
          </div>
        </el-form-item>
      </el-form>
    </Dialog>

  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import md5 from 'js-md5';
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

const formData = ref({});
const formDataRef = ref();

const checkRePassword = (rule, value, callback) => {
  if (value !== formData.value.registerPassword) {
    callback(new Error(rule.message))
  } else {
    callback();
  }
}

const rules = {
  email: [{ required: true, message: "请输入内容" },
  { validator: proxy.Verify.email, message: "请输入有效的邮箱地址", trigger: "blur" },
  ],
  password: [{ required: true, message: '请输入密码' }],
  emailCode: [{ required: true, message: '请输入邮箱验证码' }],
  nickName: [{ required: true, message: '请输入昵称' }],
  registerPassword: [{ required: true, message: "请输入密码" },
  { validator: proxy.Verify.password, message: "密码只能是8-18位的数字、字符", trigger: "blur" },
  ],
  reRegisterPassword: [{ required: true, message: "请再次输入密码" },
  { validator: checkRePassword, message: "两次输入的密码不一致", trigger: "blur" },
  ],
  checkCode: [{ required: true, message: '请输入图片验证码' }],
};

const api = {
  checkCode: '/api/checkCode',
  sendEmailCode: '/sendEmailCode',
  register: '/register',
  login: '/login',
  resetPwd: '/resetPwd',
  qqlogin: '/qqlogin'
}

const showPanel = (type) => {
  opType.value = type;
  reset();
}

onMounted(() => {
  showPanel(1);
})

// 操作类型 登录1 注册0 忘记密码2
const opType = ref(1);

// 验证码图片
const checkCodeUrl = ref(api.checkCode)
const checkCodeUrlSendEmail = ref(api.checkCode)

// 更新验证码
const changeCheckCode = (type) => {
  // 重新调用接口，并传入时间
  if (type == 0) {
    checkCodeUrl.value = api.checkCode + '?type=' + type + '&time=' + new Date().getTime()
  } else {
    checkCodeUrlSendEmail.value = api.checkCode + '?type=' + type + '&time=' + new Date().getTime()
  }
}

const formDataSendEmail = ref({});
const formDataSendEmailRef = ref();

const dialogConfig = reactive({
  show: false,
  title: "发送邮箱验证码",
  buttons: [
    {
      type: "primary",
      text: "发送验证码",
      click: (e) => {
        sendEmailCode();
      },
    },
  ],
});

// 发送邮箱验证码弹窗
const getEmailCode = () => {
  formDataRef.value.validateField('email', (valid) => {
    if (!valid) {
      return;
    }
    dialogConfig.show = true
    nextTick(() => {
      formDataSendEmailRef.value.resetFields();
      changeCheckCode(1)
      formDataSendEmail.value = {
        email: formData.value.email
      }
    })
  })
}


// 发送邮箱验证码
const sendEmailCode = () => {
  formDataSendEmailRef.value.validate(async (valid) => {
    if (!valid) {
      return
    }
    const params = Object.assign({}, formDataSendEmail.value);
    params.type = opType.value == 0 ? 0 : 1;
    let result = await proxy.Request({
      url: api.sendEmailCode,
      params: params,
      errorCallback: () => {
        changeCheckCode(1)
      }
    })
    console.log('Request result:', result); // 打印返回值
    if (!result) {
      return;
    }
    proxy.Message.success('验证码发送成功，请登录邮箱查看');
    dialogConfig.show = false;
  })
}

// 重置逻辑
const reset = () => {
  changeCheckCode(0);
  formDataRef.value.resetFields();
  formData.value = {};
  // 登录时重置之后记住密码要保存的
  if (opType.value == 1) {
    const cookieLoginInfo = proxy.vueCookies.get('loginInfo');
    if (cookieLoginInfo) {
      formData.value = cookieLoginInfo;
    }
  }
}

// 按钮
const doSubmit = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    const params = JSON.parse(JSON.stringify(formData.value));
    // 注册 找回密码 要删除一些params的数据
    if (opType.value == 0 || opType.value == 2) {
      params.password = params.registerPassword;
      delete params.registerPassword;
      delete params.reRegisterPassword
    }

    // 登录
    if (opType.value == 1) {
      let cookieLoginInfo = proxy.vueCookies.get("loginInfo");
      let cookiePassword = cookieLoginInfo == null ? null : cookieLoginInfo.password;
      // 当输入的密码与曾经点击已记住的密码不一致的话，就重新将输入的密码加密
      if (params.password != cookiePassword) {
        params.password = md5(params.password);
      }
    }
    let url = null;
    // 注册
    if (opType.value == 1) {
      url = api.login;
    }
    else if (opType.value == 0) {
      url = api.register
    }
    // 找回密码
    else if (opType.value == 2) {
      url = api.resetPwd;
    }

    let result = await proxy.Request({
      url: url,
      params: params,
      errorCallback: () => {
        changeCheckCode(0)
      }
    })
    if (!result) {
      return;
    }
    // 注册返回
    if (opType.value == 0) {
      proxy.Message.success("注册成功，请登录")
      showPanel(1);
    } else if (opType.value == 1) {
      if (params.rememberMe) {
        const loginInfo = {
          email: params.email,
          password: params.password,
          rememberMe: params.rememberMe
        };
        proxy.vueCookies.set('loginInfo', loginInfo, '7d')
      } else {
        proxy.vueCookies.remove("loginInfo")
      }
      proxy.Message.success("登录成功");
      // 存放cookie
      proxy.vueCookies.set('userInfo', result.data, '7d');
      const redirectUrl = route.query.redirectUrl || '/'
      console.log(redirectUrl);
      router.push(redirectUrl);
    } else if (opType.value == 2) {
      proxy.Message.success("重置密码成功，请登录")
      showPanel(1);
    }
  })
}

// qq登录
const qqLogin = async () => {
  let result = await proxy.Request({
    url: api.qqlogin,
    params: {
      callbackUrl: route.query.redirectUrl || '',
    }
  })
  if (!result) {
    return;
  }
  // qq登录需要请掉
  proxy.vueCookies.remove('userInfo');
  // document.location.href = result.data
}

</script>

<style lang="scss" scoped>
.login-body {
  height: 100vh;
  background: url(../assets/background.png) no-repeat center center;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;

  .checkCode-panel {
    display: flex;
    align-items: center;

    .check-code {
      cursor: pointer;
      margin-left: 10px;
      border: 1px solid #ccc;
      border-radius: 5px;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;

      &:hover {
        border-color: #4caf50;
        box-shadow: 0 4px 10px rgba(76, 175, 80, 0.2);
      }
    }
  }

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    /* 半透明遮罩 */
    z-index: 1;
    backdrop-filter: blur(5px);
    /* 模糊效果 */
  }

  .login-panel {
    position: relative;
    z-index: 2;
    /* 确保内容在遮罩层之上 */
    width: 430px;
    padding: 30px;
    background: linear-gradient(145deg, #ffffff, #f0f0f0);
    /* 渐变背景 */
    border-radius: 10px;
    /* 圆角 */
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
    /* 阴影 */
    animation: fadeIn 0.5s ease;

    @keyframes fadeIn {
      from {
        opacity: 0;
        transform: translateY(-20px);
      }

      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    .login-form {
      .login-title {
        text-align: center;
        font-size: 24px;
        font-weight: bold;
        color: #4caf50;
        /* 标题颜色 */
        margin-bottom: 30px;
      }

      .checkCode-panel {
        display: flex;
        align-items: center;

        .check-code {
          cursor: pointer;
          margin-left: 10px;
          border: 1px solid #ccc;
          border-radius: 5px;
          box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
          transition: all 0.3s ease;

          &:hover {
            border-color: #4caf50;
            box-shadow: 0 4px 10px rgba(76, 175, 80, 0.2);
          }
        }
      }

      .send-email-panel {
        width: 100%;
        display: flex;
        align-items: center;

        .el-input {
          flex: 1;
          /* 输入框占据剩余空间 */
          margin-right: 10px;
          /* 与按钮之间的间距 */
        }

        .send-email-btn {
          white-space: nowrap;
          /* 防止按钮文字换行 */
          background: linear-gradient(90deg, #4caf50, #81c784);
          /* 按钮渐变色 */
          color: #fff;
          font-weight: bold;
          border: none;
          transition: all 0.3s ease;

          &:hover {
            background: linear-gradient(90deg, #388e3c, #66bb6a);
            /* 悬停时颜色变化 */
            transform: scale(1.05);
            /* 放大效果 */
          }
        }
      }

      .remember-me {
        margin-bottom: 10px;

        .el-checkbox {
          font-size: 14px;
          color: #666;
        }
      }

      .no-account {
        display: flex;
        justify-content: space-between;
        font-size: 14px;
        width: 100%;
      }

      .login-btn {
        width: 100%;
        background: linear-gradient(90deg, #4caf50, #81c784);
        /* 渐变色 */
        border: none;
        color: #fff;
        font-size: 16px;
        font-weight: bold;
        transition: all 0.3s ease;

        &:hover {
          background: linear-gradient(90deg, #388e3c, #66bb6a);
          /* 悬停时颜色变化 */
          transform: scale(1.05);
          /* 放大效果 */
        }
      }
    }
  }

  .login-btn-qq {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
    font-size: 16px;
    color: #333;
    cursor: pointer;
    user-select: none;

    img {
      width: 28px;
      height: 28px;
      margin-left: 8px;
      border-radius: 50%;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      transition: transform 0.2s;
      vertical-align: middle;
    }

    &:hover img {
      transform: scale(1.1);
    }
  }
}
</style>
